﻿define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Distributor_redbag, GoPage,$stateParams,GoDialog, $ionicModal) {
		
		$scope.input = new Object();
		$scope.input.money = "";
		$scope.input.memo = "";
		
		$scope.$on('$ionicView.afterEnter', function(){
			$scope.store_id = $stateParams.store_id;
			$scope.advance = 0;
			if($stateParams.advance){//账号余额
				$scope.advance = $stateParams.advance;
			}
		},false)
		
		
		/******************确认支付密码**************/
		$ionicModal.fromTemplateUrl("templates/modal/confirm_pay.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_confirm = modal;
		});
		//预存款支付
		$scope.openModal_confirm = function() {
			if(!$scope.input.money){
				GoDialog.toast("请输入红包金额");
				return;
			}
			if($scope.input.money>$scope.advance){
				GoDialog.toast("红包金额不能大于账号余额");
				return;
			}
			$scope.idRedBag = true;//控制文字
			//每次打开modal，必须初始化以下2个变量
			$scope.input.password = "";
			$scope.showPotArr = new Array();
			$scope.modal_confirm.show();//满足输入条件，才弹窗
			$scope.getInputFocus();
		}
		$scope.closeModal_confirm = function(index) {
			$scope.modal_confirm.hide();
		}
		//获取焦点
		$scope.getInputFocus = function($event){
			if($event){
				$event.stopPropagation();//阻止事件冒泡
			}
			document.getElementById("inputPass").focus();
		}
		
		//输入密码监听
		$scope.$watch('input.password', function(newValue, oldValue) {
			$scope.showPotArr = new Array();//控制密码点的显示
			if(!newValue){
				return
			}
			if(newValue.length>6) {//6为密码
				newValue = newValue.substring(0, 6);
			}
			$scope.input.password = newValue;
			for (var i=0;i<$scope.input.password.length;i++) {
				$scope.showPotArr.push(i+1);
			}
			if($scope.input.password.length==6){//密码够6位，自动提交
				document.getElementById("inputPass").blur();//防止继续输入
				submitForm();
			}
		})
		/******************确认支付密码**************/
		
		//提交表单
		function submitForm(){
			if(!$scope.input.memo){
				$scope.input.memo = "恭喜发财，大吉大利";
			}
			var stores = new Array();
			stores[0] = new Object();//只有一个
			stores[0].store_id = $scope.store_id;
			Distributor_redbag.packets_grant($scope.input.money, $scope.input.memo, stores, $scope.input.password,function(data) {
				if(data.success) {
					$scope.closeModal_confirm();
					GoDialog.toast("红包发送成功");
					$scope.input = new Object();
//					GoPage.go_states("distributor_sxqd");//需要跳转到“distributor_sxqd”/"myagent"
					GoPage.go_back();
				} else {
					GoDialog.alert("提示",data.msg,function(){
						$scope.closeModal_confirm();
					});
				}
			})	
		}
		
		
	}

	controller.$inject = ['$scope', 'Distributor_redbag', 'GoPage','$stateParams','GoDialog','$ionicModal'];

	return app.registerController("distributor_redbagctrl", controller);
});